const userModel = require('../models/user')
const roleModel = require('../models/role')
const menuModel = require('../models/menu')
const jwt = require('../utils/jwt')

class User {
    static async login(ctx) {
        let { username, password } = ctx.request.body
        const info = await userModel.findOne({ username, password })
        if (info && info.status == 0) {
            return ctx.body = { code: 101, msg: '用户状态异常,请联系管理员', data: {} }
        }
        if (info && info._id) {
            const token = jwt.createToken(info)
            ctx.body = { code: 0, msg: 'success', data: { token } }
        } else {
            ctx.body = { code: -1, msg: '用户名或密码错误', data: {} }
        }
    }


    static async getUserInfo(ctx) {
        const user = ctx.user
        const userInfo = await userModel.findOne({ _id: user._id })
        // 查询非admin用户的信息
        let roleInfo = null;
        if (userInfo.role !== 'admin') {
            roleInfo = await roleModel.findOne({ role: userInfo.role })
        }
        // 测试账号 如果为非test账号，要根据roleInfo.menus字段来返回相应的菜单列表
        let menuArr = []
        if (roleInfo.role === 'test') {
            menuArr = await menuModel.find({})
        }

        ctx.body = { code: 0, msg: 'success', data: { userInfo, roleInfo, menuArr } }
    }


    static async addUser(ctx) {
        let { username, role, role_name, desc } = ctx.request.body
        const info = await userModel.findOne({ username })

        if (info && info._id) {
            ctx.body = { code: 102, msg: '用户已存在', data: {} }
        } else {
            let ele = {
                username,
                password: '123456',
                role,
                role_name,
                desc
            }
            await userModel.insertMany([ele])
            ctx.body = { code: 0, msg: 'success', data: {} }
        }
    }

    static async userList(ctx) {
        let { username, size, page } = ctx.request.query
        const params = {
            username: new RegExp(username, 'img')
        }
        size = Number(size || 4)
        page = Number(page || 1)
        if (!username) delete params.username
        const total = await userModel.find(params).count()
        const list = await userModel.find(params).skip((page - 1) * size).limit(size)
        ctx.body = { code: 0, msg: 'success', data: { total, list } }

    }

    static async updUser(ctx) {
        const { user_id, status } = ctx.request.query
        await userModel.updateOne({ _id: user_id }, { $set: { status: Number(status) } })
        ctx.body = { code: 0, msg: 'success', data: {} }
    }

    static async userDel(ctx) {
        const { user_id } = ctx.request.query
        await userModel.deleteOne({ _id: user_id })
        ctx.body = { code: 0, msg: 'success', data: {} }
    }

}

module.exports = User